#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import pycdlib
import subprocess
from .._util import Util, IsoMount
from .._const import Arch
from .._workdir import WorkDirAddonBase
from .._vm import Vm
from ._z import UtilXp, VirtualUserXp
from ._unattended import AnswerFile, CmdlinesFile, GuiRunOnceBatchFile


class WorkDirAddon(WorkDirAddonBase):

    def __init__(self, parent):
        self._parent = parent

    @property
    def installation_iso_filepath(self):
        return os.path.join(self._parent._path, "install.iso")

    @property
    def virtio_win_iso_filepath(self):
        return os.path.join(self._parent._path, "virtio-win.iso")

    @property
    def setup_driver_floppy_filepath(self):
        return os.path.join(self._parent._path, "setup_driver.ima")

    @property
    def iso_op_dirpath(self):
        return os.path.join(self._parent._path, "iso.dir")

    @property
    def floppy_op_dirpath(self):
        return os.path.join(self._parent._path, "floppy.dir")

    @property
    def tmp_file(self):
        return os.path.join(self._parent._path, "tmp.file")


class BuildUtil:

    @staticmethod
    def prepare(ts, workDirObj, srcMedia):
        # there's many quirks in windows xp installation iso file, so we only modify it, we don't recreate
        if True:
            cmdlines = []
            if "virtio" in ts.extra_drivers:
                cmdlines.append("msiexec.exe /i C:\\wstage4\\qemu-ga.msi /qn")

            iso = pycdlib.PyCdlib()
            iso.open(srcMedia.get_iso_filepath())
            try:
                # inject answer file
                answerFile = AnswerFile(ts)
                if srcMedia.get_arch() == Arch.X86:
                    dstAnswserFilePath = "/I386/" + answerFile.get_filename()
                elif srcMedia.get_arch() == Arch.X86_64:
                    dstAnswserFilePath = "/AMD64/" + answerFile.get_filename()
                else:
                    assert False
                Util.pycdlibAddFile(iso, answerFile.get_binary_content(), iso_path=dstAnswserFilePath)

                # inject "$OEM$" directory and "$OEM$/CMDLINES.TXT"file
                # windows XP iso sucks that it does not use joilet extension, ISO facade does not allow "$", so we have to use "0OEM0" as a temporary name and replace it using sed later
                if len(cmdlines) > 0:
                    Util.pycdlibAddDirectory(iso, iso_path="/0OEM0")
                    if True:
                        cmdlinesFile = CmdlinesFile([
                            "msiexec.exe /i C:\\wstage4\\qemu-ga.msi /qn",
                        ])
                        Util.pycdlibAddFile(iso, cmdlinesFile.get_binary_content(), iso_path="/0OEM0/" + cmdlinesFile.get_filename())

                iso.write(workDirObj.installation_iso_filepath)
            finally:
                iso.close()
            if len(cmdlines) > 0:
                subprocess.check_call(["sed", "-i", r"s/0OEM0/\$OEM\$/g", workDirObj.installation_iso_filepath])

        # create virtio-win.iso
        if "virtio" in ts.extra_drivers:
            subprocess.check_call(["cp", srcMedia.get_virtio_win_iso_filepath(), workDirObj.virtio_win_iso_filepath])

    @staticmethod
    def osInstall(ts, workDirObj, bDebug):
        # bootstrap: install pre dirvers for storage device, copy files
        vm = Vm(workDirObj)
        vm.set_record_file("bootstrap.mp4")
        vm.set_no_reboot(True)
        vm.use_cdrom(workDirObj.installation_iso_filepath, boot=True)
        vm.start(show=bDebug)
        try:
            vuser = VirtualUserXp("eng", vm)
            vuser.operate(vuser.BootFromCdrom())
            vm.wait_until_stop()
        except BaseException:
            vm.stop()
            raise

        # fill C:\wstage4
        with UtilXp.mountImageFile(workDirObj) as mp:
            oemDir = os.path.join(mp.drive_c_dir, "WINDOWS")        # FIXME: drivers must be put in windows dir for OemPnPDriversPath, maybe we'll change it
            # os.mkdir(oemDir)

            # https://stackoverflow.com/questions/5265377/do-the-equivalent-of-installing-a-driver-from-a-folder-programatically-in-wind
            # https://superuser.com/questions/733316/install-a-driver-in-windows-xp-from-command-line
            if "virtio" in ts.extra_drivers:
                with IsoMount(workDirObj.virtio_win_iso_filepath, workDirObj.iso_op_dirpath):
                    if ts.arch == Arch.X86:
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "Balloon", "xp", "x86"), os.path.join(oemDir, "Balloon")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "NetKVM", "xp", "x86"), os.path.join(oemDir, "NetKVM")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "qxl", "xp", "x86"), os.path.join(oemDir, "qxl")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "vioserial", "xp", "x86"), os.path.join(oemDir, "vioserial")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "viostor", "xp", "x86"), os.path.join(oemDir, "viostor")])
                        subprocess.check_call(["cp", os.path.join(workDirObj.iso_op_dirpath, "guest-agent", "qemu-ga-i386.msi"), os.path.join(oemDir, "qemu-ga.msi")])
                    elif ts.arch == Arch.X86_64:
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "Balloon", "xp", "amd64"), os.path.join(oemDir, "Balloon")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "NetKVM", "xp", "amd64"), os.path.join(oemDir, "NetKVM")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "vioserial", "xp", "amd64"), os.path.join(oemDir, "vioserial")])
                        subprocess.check_call(["cp", "-r", os.path.join(workDirObj.iso_op_dirpath, "viostor", "xp", "amd64"), os.path.join(oemDir, "viostor")])
                        subprocess.check_call(["cp", os.path.join(workDirObj.iso_op_dirpath, "guest-agent", "qemu-ga-x86_64.msi"), os.path.join(oemDir, "qemu-ga.msi")])
                    else:
                        assert False

        # install: do the installation
        vm = Vm(workDirObj)
        vm.set_record_file("install.mp4")
        vm.set_no_reboot(True)
        vm.use_cdrom(workDirObj.installation_iso_filepath)
        vm.start(show=bDebug)
        try:
            vm.wait_until_stop()
        except BaseException:
            vm.stop()
            raise

        # prepare for the first-boot
        with UtilXp.mountImageFile(workDirObj) as mp:
            guiRunOnceBatchFile = GuiRunOnceBatchFile()

            # skip windows tour
            guiRunOnceBatchFile.add_command(r'reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Applets\Tour" /v RunCount /t REG_DWORD /d 0"')

            with open(os.path.join(mp.drive_c_dir, guiRunOnceBatchFile.get_filename()), "wb") as f:
                f.write(guiRunOnceBatchFile.get_binary_content())

        # first-boot:
        vm = Vm(workDirObj)
        vm.set_record_file("first-boot.mp4")
        vm.start(show=bDebug)
        try:
            vuser = VirtualUserXp("eng", vm)
            vuser.operate(vuser.WaitFirstBoot())
            vm.shutdown()
            vm.wait_until_stop()
        except BaseException:
            vm.stop()
            raise

            # reg = WinRegistry(mp)
            # reg.add_or_modify("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "MyEntry", "REG_SZ", r'%systemroot%\system32\msiexec.exe /i "D:\guest-agent\qemu-ga-i386.msi"')

        # # install-guest-agent
        # ret = workDirObj.mount_image_file()
        # try:
        #     assert len(ret) == 1
        #     mp = list(ret.values())[0]
        #     reg = WinRegistry(mp)
        #     reg.add_or_modify("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "MyEntry", "REG_SZ", r'%systemroot%\system32\msiexec.exe /i "D:\guest-agent\qemu-ga-i386.msi"')
        # finally:
        #     workDirObj.umount_image_file()

    @staticmethod
    def cleanup(ts, workDirObj):
        # with UtilXp.mountImageFile(workDirObj) as mp:
        #     guiRunOnceBatchFile = GuiRunOnceBatchFile()
        #     os.unlink(os.path.join(mp, guiRunOnceBatchFile.get_filename()))
        #
        #     shutil.rmtree(os.path.join(mp, "wstage4"))
        pass
